package server.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.CharsetUtil;
import javax.net.ssl.SSLEngine;

public class SslChannelInitializer extends ChannelInitializer<Channel> {

  private final SslContext context;

  public SslChannelInitializer(SslContext context){
    this.context = context;
  }

  @Override
  protected void initChannel(Channel ch) throws Exception {
    SSLEngine engine = context.newEngine(ch.alloc());
    engine.setUseClientMode(false);
    ch.pipeline().addFirst("ssl",new SslHandler(engine));
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("frameDecoder",new LengthFieldBasedFrameDecoder(1024,04,04));
    pipeline.addLast("frameEncoder",new LengthFieldPrepender(4));
    pipeline.addLast("decoder",new StringDecoder(CharsetUtil.UTF_8));
    pipeline.addLast("encoder",new StringEncoder(CharsetUtil.UTF_8));
    pipeline.addLast("spiderServerBusiHandler",new SpiderServerBusiHandler());

  }
}
